package com.honghu.villagepost.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.honghu.villagepost.R
import com.honghu.villagepost.adapter.ItemTypeAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseActivity
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.entity.Addr
import com.honghu.villagepost.entity.Select
import com.honghu.villagepost.entity.request.LogisticsOrderReq
import com.honghu.villagepost.widget.DateSelectPopup
import com.honghu.villagepost.widget.ItemTypeSelectPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_logistics_order_settle.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author: mqwang
 * @create: 3/2/21 9:44 AM
 * @Description: 寄件订单结算
 */
class LogisticsOrderSettleActivity : BaseActivity() {

    /** 0-寄件，1-收件*/
    private var selectAddrType: Int = 0
    private var logisticsOrderReq: LogisticsOrderReq = LogisticsOrderReq()

    companion object{
        val TYPE_SEND: Int = 1//速配寄件
        val TYPE_LINDAN_SEND: Int = 2//零担寄件
        val TYPE_CITY_SEND: Int = 3//同城速递
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_logistics_order_settle
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {

        setMainTitle("快速寄件")

        tv_ji_addr.setOnClickListener {
            selectAddrType = 0
            AddrActivity.self(this, true)
        }
        send_ll.setOnClickListener {
            selectAddrType = 0
            if (logisticsOrderReq != null && logisticsOrderReq.senderAddress != null) {
                AddAddrActivity.self(this, logisticsOrderReq.senderAddress!!)
            } else {
                AddAddrActivity.self(this)
            }
        }

        tv_shou_addr.setOnClickListener {
            selectAddrType = 1
            AddrActivity.self(this, true)
        }
        rece_ll.setOnClickListener {
            selectAddrType = 1
            if (logisticsOrderReq != null && logisticsOrderReq.receiverAddress != null) {
                AddAddrActivity.self(this, logisticsOrderReq.receiverAddress!!)
            } else {
                AddAddrActivity.self(this)
            }
        }

        tv_door_time.setOnClickListener {
            showDoorTimePopup()
        }

        recycler_view.setLayoutManager(GridLayoutManager(this, 3))
        val itemTypeAdapter = ItemTypeAdapter()
        itemTypeAdapter.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener {
            override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val selectItem = itemTypeAdapter.selectItem(position)
                logisticsOrderReq.goodsInfo = selectItem.name
                settleOrder()
            }
        })
        recycler_view.setAdapter(itemTypeAdapter)
        itemTypeAdapter.addData(Select(false, "汽配"))
        itemTypeAdapter.addData(Select(false, "手机配件"))
        itemTypeAdapter.addData(Select(false, "食品"))
        itemTypeAdapter.addData(Select(false, "其他"))
        btn_sku_quantity_minus.setOnClickListener(View.OnClickListener {
            val quantity: String = et_sku_quantity_input.getText().toString()
            if (TextUtils.isEmpty(quantity)) {
                return@OnClickListener
            }
            val quantityInt = quantity.toInt()
            if (quantityInt > 1) {
                val newQuantity = (quantityInt - 1).toString()
                et_sku_quantity_input.setText(newQuantity)
                logisticsOrderReq.weight = newQuantity
            }
            settleOrder()
        })

        btn_sku_quantity_plus.setOnClickListener(View.OnClickListener {
            val quantity: String = et_sku_quantity_input.getText().toString()
            if (TextUtils.isEmpty(quantity)) {
                return@OnClickListener
            }
            var quantityInt = quantity.toInt()
            quantityInt++
            et_sku_quantity_input.setText(quantityInt.toString())
            logisticsOrderReq.weight = quantityInt.toString()
            settleOrder()
        })

//        tv_item_information.setOnClickListener {
//            showItemInformationPopup()
//        }

        rg_type.setOnCheckedChangeListener { group, checkedId ->
            settleOrder()
        }

        tv_confirm.setOnClickListener {

            if (logisticsOrderReq.senderAddress == null || TextUtils.isEmpty(logisticsOrderReq.senderAddress!!.name)){
                ToastUtils.showShort("请选择")
                return@setOnClickListener

            }

            val userRemo = et_remark.text.toString();
            logisticsOrderReq.userMemo = userRemo;
            ApiService.logistics_orde_create(this, logisticsOrderReq, object : DialogCallback<LzyResponse<MutableMap<String, Any>>>(this) {
                override fun onSuccess(response: Response<LzyResponse<MutableMap<String, Any>>>?) {
                    ToastUtils.showShort("下单成功")
                    val orderNo = response!!.body().data.get("logisticsNo") as String?
                    LogisticsOrderDetailsActivity.self(mContext, orderNo!!)
                }
            })
        }

    }

    fun showDoorTimePopup() {
        XPopup
                .Builder(this)
                .autoOpenSoftInput(true)
                .setPopupCallback(object : SimpleCallback() {
                    override fun onDismiss(popupView: BasePopupView?) {
                        super.onDismiss(popupView)

                    }
                })
                .asCustom(DateSelectPopup(this, object : DateSelectPopup.DateCallBack {
                    override fun showValue(value: Select) {
                        tv_door_time.setText(value.name + value.startTime + "-" + value.endTime)

                        val sf = SimpleDateFormat("yyyy-MM-dd")
                        val c = Calendar.getInstance()
                        c.add(Calendar.DAY_OF_MONTH, 1)

                        val startSf = sf.format(c.time) + " " + value.startTime + ":00"
                        val startDate = TimeUtils.string2Date(startSf)
                        logisticsOrderReq.pickUpStartTime = startDate.time

                        c.add(Calendar.DAY_OF_MONTH, 1)
                        val endSf = sf.format(c.time) + " " + value.endTime + ":00"
                        val endDate = TimeUtils.string2Date(endSf)

                        logisticsOrderReq.pickUpEndTime = endDate.time

                    }

                }))
                .show()

    }

    fun showItemInformationPopup() {
        XPopup
                .Builder(this)
                .autoOpenSoftInput(true)
                .setPopupCallback(object : SimpleCallback() {
                    override fun onDismiss(popupView: BasePopupView?) {
                        super.onDismiss(popupView)

                    }
                })
                .asCustom(ItemTypeSelectPopup(this, object : ItemTypeSelectPopup.PopCallBack {
                    override fun showValue(goodsInfo: String?, weight: String?) {
//                        tv_item_information.setText(goodsInfo)
                        logisticsOrderReq.goodsInfo = goodsInfo!!
                        logisticsOrderReq.weight = weight!!
                        settleOrder()
                    }
                }))
                .show()

    }

    fun settleOrder() {
        if (logisticsOrderReq.senderAddress == null){
            return
        }

        if (logisticsOrderReq.receiverAddress == null){
            return
        }

        if (TextUtils.isEmpty(logisticsOrderReq.goodsInfo)){
            return
        }
        if (rb_jf.isChecked) {
            logisticsOrderReq.payType = 1
        } else {
            logisticsOrderReq.payType = 2
        }
        ApiService.logistics_order_settle(this, logisticsOrderReq, object : DialogCallback<LzyResponse<LogisticsOrderReq>>() {
            override fun onSuccess(response: Response<LzyResponse<LogisticsOrderReq>>?) {
                tv_total.setText(getString(R.string.price_format, response!!.body().data.payment))

            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: Addr) {
        when (selectAddrType) {
            0 -> {
                send_ll.setText("")
                tv_send_name.setText(item.name)
                tv_send_phone.setText(item.mobile)
                tv_send_addr.setText(item.province + item.city + item.district)
                logisticsOrderReq.senderAddress = item
            }
            1 -> {
                rece_ll.setText("")
                tv_receiver_name.setText(item.name)
                tv_receiver_phone.setText(item.mobile)
                tv_receiver_addr.setText(item.province + item.city + item.district)
                logisticsOrderReq.receiverAddress = item

            }
        }
    }

}